package com.sttk.fastMark.camera.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sttk.fastMark.camera.AppConfig;
import com.sttk.fastMark.camera.BaseAc;
import com.sttk.fastMark.camera.R;
import com.sttk.fastMark.camera.adapter.ColorAdapter;
import com.sttk.fastMark.camera.bean.ColorBean;
import com.sttk.fastMark.camera.bean.WatermarkBean;
import com.sttk.fastMark.camera.databinding.ActivityEditCommonWatermarkBinding;
import com.sttk.fastMark.camera.dialog.InspectorDialog;
import com.sttk.fastMark.camera.dialog.LocationDialog;
import com.sttk.fastMark.camera.dialog.PermissionExplainDialog;
import com.sttk.fastMark.camera.dialog.SelDateDialog;
import com.sttk.fastMark.camera.dialog.SelHourDialog;
import com.sttk.fastMark.camera.dialog.ThemeDialog;
import com.sttk.fastMark.camera.utils.AppSpUtils;
import com.sttk.fastMark.camera.view.RoundedLinearLayout;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class EditCommonWatermarkActivity extends BaseAc<ActivityEditCommonWatermarkBinding> implements View.OnClickListener, OnItemClickListener {

    public static int selPosition;
    private WatermarkBean.CommonBean commonBean;
    private ColorAdapter colorAdapter;
    private List<ColorBean> listColor;
    private int colorPos;

    @Override
    protected int onCreate() {
        return R.layout.activity_edit_common_watermark;
    }

    @Override
    protected void initView() {
        mDataBinding.ivEditCommonWatermarkBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.tvSave.setOnClickListener(this);
        mDataBinding.llTheme.setOnClickListener(this);
        mDataBinding.llDate.setOnClickListener(this);
        mDataBinding.llTime.setOnClickListener(this);
        mDataBinding.llPeople.setOnClickListener(this);
        mDataBinding.llLocation.setOnClickListener(this);
        mDataBinding.tvPositioning.setOnClickListener(this);

        mDataBinding.rvColorList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        colorAdapter = new ColorAdapter();
        mDataBinding.rvColorList.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.llTheme) {//主题
            showThemeDialog();
        } else if (id == R.id.llDate) {//日期
            showSelDateDialog();
        } else if (id == R.id.llTime) {//时间
            showSelHourDialog();
        } else if (id == R.id.llPeople) {//检查员
            showInspectorDialog();
        } else if (id == R.id.tvPositioning) {//定位
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                getLocationPermission();
            } else {
                //获取定位
                initLocation();
            }
        } else if (id == R.id.llLocation) {//地点
            showLocationDialog();
        } else if (id == R.id.tvSave) {//保存
            List<WatermarkBean> listSp = AppSpUtils.getWatermarkList();
            listSp.get(selPosition).setCommonBean(commonBean);
            AppSpUtils.saveWatermarkList(listSp);
            ToastUtils.showShort(getString(R.string.save_suc));
            finish();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        listColor.get(colorPos).setSelected(false);
        commonBean.setThemeColor(listColor.get(position).getColor());
        setData();
    }

    @Override
    protected void initData() {
        commonBean = AppSpUtils.getWatermarkList().get(selPosition).getCommonBean();

        listColor = new ArrayList<>();
        listColor.add(new ColorBean("#000000", false));
        listColor.add(new ColorBean("#FF6464", false));
        listColor.add(new ColorBean("#EBC527", false));
        listColor.add(new ColorBean("#FAFD00", false));
        listColor.add(new ColorBean("#13FD00", false));
        listColor.add(new ColorBean("#00C497", false));
        listColor.add(new ColorBean("#3D78FE", false));
        listColor.add(new ColorBean("#FF29FD", false));

        setData();
    }

    private void setData() {
        mDataBinding.llPeople.setVisibility(View.GONE);

        mDataBinding.llWatermark.removeAllViews();
        View view = null;

        if (selPosition == 1) {
            view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark1, null, false);

            TextView tvTheme = view.findViewById(R.id.tvTheme);
            TextView tvPeople = view.findViewById(R.id.tvPeople);

            tvTheme.setText(commonBean.getTheme());
            mDataBinding.tvTheme.setText(commonBean.getTheme());
            mDataBinding.llPeople.setVisibility(View.VISIBLE);
            if (commonBean.getPeople() != null) {
                tvPeople.setText(getString(R.string.inspector) + "：" + commonBean.getPeople());
                mDataBinding.tvPeople.setText(commonBean.getPeople());
            } else {
                tvPeople.setText(getString(R.string.inspector) + "：" + getString(R.string.click_edit_content));
                mDataBinding.tvPeople.setText(getString(R.string.click_edit));
            }
            for (int i = 0; i < listColor.size(); i++) {
                ColorBean colorBean = listColor.get(i);
                if (colorBean.getColor().equals(commonBean.getThemeColor())) {
                    colorPos = i;
                    colorBean.setSelected(true);
                    break;
                }
            }
            colorAdapter.setList(listColor);
        } else if (selPosition == 2) {
            view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark2, null, false);

            TextView tvTheme = view.findViewById(R.id.tvTheme);

            tvTheme.setText(commonBean.getTheme());
            mDataBinding.tvTheme.setText(commonBean.getTheme());

            for (int i = 0; i < listColor.size(); i++) {
                ColorBean colorBean = listColor.get(i);
                if (colorBean.getColor().equals(commonBean.getThemeColor())) {
                    colorPos = i;
                    colorBean.setSelected(true);
                    break;
                }
            }
            colorAdapter.setList(listColor);
        } else if (selPosition == 3 || selPosition == 4 || selPosition == 5) {
            mDataBinding.tvTheme.setText(commonBean.getTheme());
            mDataBinding.tvLocationTitle.setText(getString(R.string.location));

            if (selPosition == 3) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark3, null, false);
            } else if (selPosition == 4) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark4, null, false);
            } else {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark5, null, false);
            }

            TextView tvTheme = view.findViewById(R.id.tvTheme);

            tvTheme.setText(commonBean.getTheme());
            mDataBinding.tvTheme.setText(commonBean.getTheme());

            for (int i = 0; i < listColor.size(); i++) {
                ColorBean colorBean = listColor.get(i);
                if (colorBean.getColor().equals(commonBean.getThemeColor())) {
                    colorPos = i;
                    colorBean.setSelected(true);
                    break;
                }
            }
            colorAdapter.setList(listColor);
        } else {
            mDataBinding.llTheme.setVisibility(View.GONE);
            mDataBinding.tvLocationTitle.setText(getString(R.string.location));
            mDataBinding.llColor.setVisibility(View.GONE);

            if (selPosition == 6) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark6, null, false);
            } else if (selPosition == 7) {
                view = LayoutInflater.from(this).inflate(R.layout.layout_common_watermark7, null, false);
            }
        }

        TextView tvDate = view.findViewById(R.id.tvDate);
        TextView tvTime = view.findViewById(R.id.tvTime);
        TextView tvWeek = view.findViewById(R.id.tvWeek);
        TextView tvLocation = view.findViewById(R.id.tvLocation);

        tvDate.setText(AppConfig.DATE);
        mDataBinding.tvDate.setText(AppConfig.DATE);
        tvTime.setText(AppConfig.TIME);
        mDataBinding.tvTime.setText(AppConfig.TIME);
        long mill = TimeUtils.string2Millis(AppConfig.DATE, new SimpleDateFormat("yyyy-MM-dd"));
        tvWeek.setText(TimeUtils.millis2String(mill, new SimpleDateFormat("EEEE")));
        if (commonBean.getLocation() != null) {
            if (selPosition == 1) {
                tvLocation.setText(getString(R.string.inspection_location) + "：" + commonBean.getLocation());
            } else {
                tvLocation.setText(commonBean.getLocation());
            }
            if (TextUtils.isEmpty(commonBean.getLocation())) {
                mDataBinding.tvLocation.setText(getString(R.string.click_edit));
            } else {
                mDataBinding.tvLocation.setText(commonBean.getLocation());
            }
        } else {
            tvLocation.setText(getString(R.string.inspection_location) + "：" + getString(R.string.click_edit_content));
            mDataBinding.tvLocation.setText(getString(R.string.click_edit));
        }
        if (selPosition != 6 && selPosition != 7) {
            RoundedLinearLayout llWatermarkBg = view.findViewById(R.id.llWatermarkBg);
            llWatermarkBg.setBackgroundColor(Color.parseColor(listColor.get(colorPos).getColor()));
        }
        // 设置llWatermark的宽度与加载的水印布局一致
        ViewGroup.LayoutParams params = mDataBinding.llWatermark.getLayoutParams();
        switch (selPosition) {
            case 1:
                params.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 229, getResources().getDisplayMetrics());
                break;
            case 2:
                params.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 230, getResources().getDisplayMetrics());
                break;
            case 3:
            case 4:
            case 5:
                params.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 240, getResources().getDisplayMetrics());
                break;
            case 6:
            case 7:
                // layout_common_watermark6和7的宽度都是240dp
                params.width = (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 240, getResources().getDisplayMetrics());
                break;
            default:
                params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
                break;
        }
        mDataBinding.llWatermark.setLayoutParams(params);

        mDataBinding.llWatermark.addView(view);
    }

    private void showThemeDialog() {
        ThemeDialog dialog = new ThemeDialog(mContext);
        dialog.setText(mDataBinding.tvTheme.getText().toString());
        dialog.setListener(new ThemeDialog.Ilistener() {
            @Override
            public void clickConfirm(String text) {
                commonBean.setTheme(text);
                setData();
            }
        });
        dialog.show();
    }

    private void showSelDateDialog() {
        SelDateDialog dialog = new SelDateDialog(mContext);
        dialog.setListener(new SelDateDialog.Ilistener() {
            @Override
            public void clickConfirm(long date) {
                AppConfig.DATE = TimeUtils.millis2String(date, new SimpleDateFormat("yyyy-MM-dd"));
                setData();
            }
        });
        dialog.show();
    }

    private void showSelHourDialog() {
        SelHourDialog dialog = new SelHourDialog(mContext);
        dialog.setListener(new SelHourDialog.Ilistener() {
            @Override
            public void clickConfirm(long date) {
                AppConfig.TIME = TimeUtils.millis2String(date, new SimpleDateFormat("yyyy-MM-dd"));
                setData();
            }
        });
        dialog.show();
    }

    private void showInspectorDialog() {
        InspectorDialog dialog = new InspectorDialog(mContext);
        dialog.setText(mDataBinding.tvPeople.getText().toString());
        dialog.setListener(new InspectorDialog.Ilistener() {
            @Override
            public void clickConfirm(String text) {
                commonBean.setPeople(text);
                setData();
            }
        });
        dialog.show();
    }

    private void showLocationDialog() {
        LocationDialog dialog = new LocationDialog(mContext);
        dialog.setText(mDataBinding.tvLocation.getText().toString());
        dialog.setListener(new LocationDialog.Ilistener() {
            @Override
            public void clickConfirm(String text) {
                commonBean.setLocation(text);
                setData();
            }
        });
        dialog.show();
    }

    private void getLocationPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_location_permission));
        PermissionUtils.permission(Manifest.permission.ACCESS_FINE_LOCATION).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                initLocation();
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    private LocationManager mLocationMgr; // 声明一个定位管理器对象


    private boolean isLocationEnable = false; // 定位服务是否可用

    public void initLocation() {
        mLocationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria(); // 创建一个定位准则对象
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 设置定位精确度
        criteria.setAltitudeRequired(true); // 设置是否需要海拔信息
        criteria.setBearingRequired(true); // 设置是否需要方位信息
        criteria.setCostAllowed(true); // 设置是否允许运营商收费
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 设置对电源的需求
        // 获取定位管理器的最佳定位提供者
        String bestProvider = mLocationMgr.getBestProvider(criteria, true);
        if (bestProvider != null && mLocationMgr.isProviderEnabled(bestProvider)) { // 定位提供者当前可用
            beginLocation(bestProvider); // 开始定位
            isLocationEnable = true;
        } else { // 定位提供者暂不可用
            ToastUtils.showShort(getString(R.string.please_open_location_service));
            isLocationEnable = false;
        }
    }

    private void beginLocation(String method) {

        // 检查当前设备是否已经开启了定位功能

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)

                != PackageManager.PERMISSION_GRANTED) {
            ToastUtils.showShort(getString(R.string.please_open_location_permission));
            return;

        }

        // 设置定位管理器的位置变更监听器

        mLocationMgr.requestLocationUpdates(method, 300, 0, mLocationListener);

        // 获取最后一次成功定位的位置信息

        Location location = mLocationMgr.getLastKnownLocation(method);
        if (location != null) {
            setLocation(location); // 显示定位结果文本
        }


    }
    // 定义一个位置变更监听器

    private LocationListener mLocationListener = new LocationListener() {

        @Override

        public void onLocationChanged(Location location) {
            if (location != null) {
                setLocation(location); // 显示定位结果文本
            }
        }

        @Override

        public void onProviderDisabled(String arg0) {
        }

        @Override

        public void onProviderEnabled(String arg0) {
        }

        @Override

        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        }

    };

    private void setLocation(Location location) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        // 获取并显示位置名称
        String locationStr = getLocationName(latitude, longitude);
        if (!TextUtils.isEmpty(locationStr)) {
            commonBean.setLocation(locationStr);
            setData();
            mLocationMgr.removeUpdates(mLocationListener);
        }

    }

    private String getLocationName(double lat, double lon) {
        // 创建DecimalFormat实例用于格式化经纬度
        DecimalFormat df = new DecimalFormat("#.#####");

        // 方案1：使用Android原生Geocoder
        if (Geocoder.isPresent()) {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
                if (!addresses.isEmpty()) {
                    Address address = addresses.get(0);
                    StringBuilder sb = new StringBuilder();
//                    for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
//                        sb.append(address.getAddressLine(i)).append("\n");
//                    }
                    sb.append(address.getAddressLine(0));
                    String fullAddress = sb.toString();
                    return fullAddress;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}